import utime as time
import app_network
from umqttsimple import MQTTClient
import ustruct
import ujson
from driver import TIMER
qos = 1
_get_topic = "attributes/push" 
_update_topic = "attributes"  #上报属性
update_data_topic = "data/test"  #原始数据上报



def on_message(topic, message):
    print("Received message:", topic, message)
    

def mqtt_connect():
    global client
    global update_topic

    username = "*****"  
    clientId = "Testhaas506"
    password = "*****" 
 
    mqttaddr = "sh-1-mqtt.iot-api.com"
    serverport = 1883
    hearttime = 50
    #订阅/发布的topic
    get_topic = _get_topic
    update_topic = _update_topic

    client = MQTTClient(clientId, mqttaddr,serverport,username,password,hearttime)  # 建立一个MQTT客户端
    client.set_callback(on_message)  # 设置回调函数
    ret = client.connect()  # 建立连接
    print('connect ret ={}'.format(ret))
    client.subscribe(get_topic)  # 监控ledctl这个通道，接收控制命令


def print_hex(_bytes):   
    _val = [hex(int(i)) for i in _bytes]
    print(' '.join(_val))

# 转换Json格式1为字符串数组
def convert_json_format1(_body):
    packet_type = 0x01
    packet = bytearray()
    packet.extend(ustruct.pack("!B", packet_type))   # 首先填充数据点类型值
    packet_content = ujson.dumps(_body)      # 将Json格式数据转换为字符串
    if isinstance(packet_content, str):
        packet_content = packet_content.encode('utf-8')
        packet_content_length = len(packet_content)
        # 填充json字符串长度和json字符串
        packet.extend(ustruct.pack("!H" + str(packet_content_length) + "s", packet_content_length, packet_content))
    print_hex(packet)
    return packet

#发送字节码数据
def update_data():
    global client
    global update_topic
    data={"test":{"state":1}}
    payload1 = convert_json_format1(data)   
    # print(repr(string1))  
    # print(type(string1))
    client.publish(update_data_topic, payload1.decode('utf-8'))
    # return payload1.decode('utf-8')

def update_json():
    global client
    global update_topic
    send_data = {
        "version":"1.0",
        "temperature":28.8,
        "led":1
    }
    client.publish(update_topic, ujson.dumps(send_data))
    # return ujson.dumps(send_data)

# 发送心跳包
def cb1(args):
    global count
    global client
    print("count:",count)
    count+=1
    client.ping()

def main():
    global client
    global count
    count = 0
    print('main enter')
    ret = app_network.connect_network()
    if ret == 0:
        mqtt_connect()
        # update_json()
        update_data()
    else:
        print('network-connection failed')
    timerObj = TIMER(0)
    ret = timerObj.open(mode=timerObj.PERIODIC, period=30000, callback=cb1)
    while True:
        client.check_msg()
        time.sleep(10)

if __name__ == '__main__':
    main()